package com.sservice.web.controller.admin;

import com.sservice.banfu.service.TplService;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.CompareObject;
import com.sservice.common.Constants;
import com.sservice.common.SameUrlData;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.e.DataR;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.service.DataRService;
import com.sservice.model.entity.SaleLevel;
import com.sservice.service.service.*;
import com.sservice.urp.dao.IUserDao;
import com.sservice.urp.dao.IUserRoleDao;
import com.sservice.urp.dao.UserSettingMapper;
import com.sservice.urp.e.Setting;
import com.sservice.urp.entity.*;
import com.sservice.urp.service.SettingService;
import com.sservice.urp.vo.UserVo;
import com.sservice.web.common.StringUtils;
import com.sservice.web.log.Action;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/user")
public class UserController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserDao userDao;
    @Autowired
    private SettingService settingService;
    @Autowired
    private UserSettingMapper settingDao;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IComService comService;

    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private ISaleLevelService slService;
    @Autowired
    private ISysLogService sysLogService;
    @Autowired
    private TplService tplService;
    @Autowired
    private CategoryService categoryService;

    /**
     * 获取登录用户签章
     *
     * @param user
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @ResponseBody
    @RequestMapping(value = "/getSignature", method = RequestMethod.GET)
    public BaseResult<Object> getSignature(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User u = (User) request.getSession().getAttribute(Constants.USER);
        Com com = comService.selectByPrimaryKey(Integer.valueOf(u.getComid()));
        if (com == null) {
            return new BaseResult(false, "超级管理员不能授权签章");
        }
        com.setTel(String.valueOf(u.getId()));
        return new BaseResult(true, com);
    }

    /**
     * 设置前端首页
     *
     * @param user
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */

    @ResponseBody
    @SameUrlData
    @RequestMapping(value = "/setHome", method = RequestMethod.POST)
    public BaseResult<Object> setHome(User user) {
        tplService.setHome(user.getId()); //设置home
        Category category = new Category();
        category.setType1("front-menu");
        category.setName("首页");
        Category category1 = categoryService.selectBy(category);
        if (category1 == null) {
            return new BaseResult(false, "菜单未设置首页", 403);
        }
        category.setRemark(user.getPassword());
        category.setId(category1.getId());

        return new BaseResult(true, categoryService.updateByPrimaryKeySelective(category));
    }

    /***
     * 用户设置
     * @param user
     * @param request
     * @return
     * @throws NoSuchMethodException
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     */
    @ResponseBody
    @RequestMapping(value = "/setting", method = RequestMethod.POST)
    public BaseResult<Object> setting(UserSetting user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User u = (User) request.getSession().getAttribute(Constants.USER);
        user.setUserId(String.valueOf(u.getId()));
        UserSetting com_ = settingDao.selectBy(user);
        int com = 0;
        if (com_ != null) {
            com = settingDao.updateByPrimaryKeySelective(user);
        } else {
            com = settingDao.insertSelective(user);
        }
        return new BaseResult(true, com);
    }

    @ResponseBody
    @RequestMapping(value = "/getSetting", method = RequestMethod.POST)
    public BaseResult<Object> getSetting(UserSetting user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User u = (User) request.getSession().getAttribute(Constants.USER);
        user.setUserId(String.valueOf(u.getId()));
        UserSetting com = settingDao.selectBy(user);
        return new BaseResult(true, com);
    }

    @Autowired
    DataRService dataRService;

    /**
     * 用户创建
     *
     * @return
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public BaseResult<Object> create(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

        BaseResult<Object> res;

        if (StringUtils.isNoneBlank(user.getType())) {
            if (user.getComid() == 0) { //不传递值时自动赋值当前用户所在ID
                UserVo u = userService.getLoginedUser(request);
                user.setComid(u.getComid());
            }
            User user1 = userService.queryUserByPhone(user.getPhone());
            if (user1 != null) {
                return new BaseResult(false, "手机号已经被占用", 403);
            }
            user.setPassword("e10adc3949ba59abbe56e057f20f883e");// 默认密码123456
            userService.insertSelective(user);
            List dataR = new ArrayList();
            DataR dataR1 = new DataR();
            dataR1.setSourceId(user.getId());//
            dataR1.setType1(user.getType());
            dataR.add(dataR1);//  角色关系
            dataRService.addBatch(dataR);
            return new BaseResult(true, user.getId());
        }
        User u = new User();

        u.setUserName(user.getUserName());
        User us = userService.queryUserByPhoneOrUserName(u);
        if (us != null) {
            return new BaseResult(false, "用户名已占用!", 403);
        }
        u.setUserName(null);
        u.setPhone(user.getPhone());
        User usv = userService.queryUserByPhoneOrUserName(u);
        if (usv != null) {
            return new BaseResult(false, "手机号已占用!", 403);
        }
        UserVo vo = new UserVo();
        vo.setComid(user.getComid());
        int number = userService.queryCountByComId(vo);
        String jobNum = "";
        int len = (user.getComid() + jobNum).length();
        for (int i = 0; i < 3 - len; i++) { //企业ID3位，不足3位用0补齐
            jobNum += "0";
        }
        jobNum += user.getComid();

        String number_ = "" + (number + 1);
        for (int i = 0; i < 5 - number_.length(); i++) { //工号5位
            jobNum += "0";
        }
        jobNum += number_;
//        jobNum = String.valueOf(user.getComid()).length()
        user.setJobNum(jobNum); // 密码加密
        int service_res = userService.insertSelective(user);
        if (service_res > 0) {
            sysLogService.log("创建", request, Integer.valueOf(user.getId()), Action.userType);
        }
        res = new BaseResult(true, service_res);
        return res;
    }


    @ResponseBody
    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    public BaseResult<Object> reset(User user, HttpSession session, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        User u = (User) session.getAttribute(Constants.USER);
        user.setId(u.getId());
        int service_res = userService.updateByPrimaryKeySelective(user);
        if (service_res > 0) {
            sysLogService.log("重置密码", request, Integer.valueOf(user.getId()), Action.userType);
        }
        BaseResult<Object> res = new BaseResult(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Integer> delete(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        user.setStatus("3");
        int service_res = userService.updateByPrimaryKeySelective(user);
        if (service_res > 0) {
            sysLogService.log("删除", request, Integer.valueOf(user.getId()), Action.userType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /**
     * 离职
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/off", method = RequestMethod.POST)
    public BaseResult<Integer> off(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        user.setStatus("0");
        int service_res = userService.updateByPrimaryKeySelective(user);
        if (service_res > 0) {
            sysLogService.log("离职", request, Integer.valueOf(user.getId()), Action.userType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/on", method = RequestMethod.POST)
    public BaseResult<Integer> on(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        user.setStatus("1");
        int service_res = userService.updateByPrimaryKeySelective(user);
        if (service_res > 0) {
            sysLogService.log("恢复", request, Integer.valueOf(user.getId()), Action.userType);
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Integer> update(User user, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        if (StringUtils.isNoneBlank(user.getType())) {
            int service_res = userService.updateByPrimaryKeySelective(user);
            return new BaseResult(true, service_res);
        }
        User user_ = userService.selectDepByPrimaryKey(user);
        int service_res = userService.updateByPrimaryKeySelective(user);
        if (service_res > 0) {
            Map<String, Object> res = CompareObject.contrastObj(user, user_);
            if (res.get("password") != null) {
                sysLogService.log("修改密码", request, Integer.valueOf(user.getId()), Action.userType);
            } else {
                sysLogService.log(res, request, Integer.valueOf(user.getId()), Action.userType);
            }
        }
        BaseResult<Integer> res = new BaseResult<Integer>(true, service_res);
        return res;
    }

    /***
     * 更新用户角色
     * @param id
     * @param roles
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/role_update", method = RequestMethod.POST)
    public BaseResult<Object> roleUpdate(String id, String logs, String roles, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        if (id != null || !"".equals(id) || roles.length() == 0) {
            userService.deleteByUserId(Integer.valueOf(id));
            String[] roleArr = roles.split(",");
            List<UserRole> list = new ArrayList<UserRole>();
            for (String role : roleArr) {
                UserRole ur = new UserRole();
                ur.setRoleId(Integer.valueOf(role));
                ur.setUserId(Integer.valueOf(id));
                list.add(ur);
            }
            int res = userService.addBatch(list);
            if (res > 0) {
                sysLogService.log(logs, request, Integer.valueOf(id), Action.userType);
            }
            return new BaseResult<Object>(true, userService.addBatch(list));

        } else {
            return new BaseResult<Object>(false, "参数错误", 403);
        }
    }

    @Autowired
    IUserRoleDao iUserRoleDao;

    @ResponseBody
    @RequestMapping(value = "/role_add", method = RequestMethod.POST)
    public BaseResult<Object> roleAdd(String userId, String roleId, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        List list = new ArrayList();
        UserRole userRole = new UserRole();
        userRole.setUserId(Integer.valueOf(userId));
        userRole.setRoleId(Integer.valueOf(roleId));
        list.add(userRole);
        return new BaseResult(true, iUserRoleDao.addBatch(list));
    }

    @ResponseBody
    @RequestMapping(value = "/role_del", method = RequestMethod.POST)
    public BaseResult<Object> roleDel(String userId, String roleId, HttpServletRequest request) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        List list = new ArrayList();
        UserRole userRole = new UserRole();
        userRole.setUserId(Integer.valueOf(userId));
        userRole.setRoleId(Integer.valueOf(roleId));
        iUserRoleDao.deleteBy(userRole);
        return new BaseResult(true, 1);
    }

    @ResponseBody
    @RequestMapping(value = "/get_user_role", method = RequestMethod.GET)
    public ListResult<List> getUserRole(String id) {
        List<Role> list = roleService.getRolesByUserID(Integer.valueOf(id));
        ListResult<List> res = new ListResult(true, list);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/modify", method = RequestMethod.POST)
    public BaseResult<User> modify(User user) {
        BaseResult<User> res = new BaseResult<User>(true, new User());
        return res;
    }

    /***
     * 分页查询
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult query(UserVo user) {
        List<User> list = userService.queryByPage(user);
        int total = userService.countByPage(user);
        user.getPage();
        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/queryPlain", method = RequestMethod.GET)
    public ListResult queryPlain(UserVo user, HttpServletRequest request, boolean isUser) {
        if (!isUser) {
            if (user.getComid() == 0) {
                UserVo u = userService.getLoginedUser(request);
                user.setComid(u.getComid());
            }
        }
        List<User> list = userService.queryPlainByPage(user);
        int total = userService.countPlainByPage(user);
        user.getPage();
        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 按关系进行查询
     *
     * @param user
     * @param request
     * @param isUser
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryPlainWithDr", method = RequestMethod.GET)
    public ListResult queryPlainWithDr(UserVo user, HttpServletRequest request, boolean isUser) {
        if (!isUser) {
            if (user.getComid() == 0 && !"all".equals(user.getCode())) {
                UserVo u = userService.getLoginedUser(request);
                user.setComid(u.getComid());
            }
        }
        List<UserVo> list = userService.queryPlainWithDr(user);
        int total = userService.countPlainWithDr(user);
        user.getPage();
        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    /**
     * 营运
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/operator", method = RequestMethod.GET)
    public ListResult operator(UserVo user) {
        List<User> list = userService.queryByPage(user);
        int total = userService.queryCount(user);

        Pagination page = new Pagination(user.getPage(), total, user.getSize());
        ListResult res = new ListResult(true, list);
        res.setPage(page);

        return res;
    }

    /**
     * 所有
     *
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public ListResult all(UserVo user) {
        List<User> list = userDao.queryAll1(user);
        return new ListResult(true, list);
    }

    @ResponseBody
    @RequestMapping(value = "/no-login")
    public BaseResult auth(HttpServletRequest request) {
        return new BaseResult<String>(false, "未登录!", 401);
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public BaseResult<User> logout(User arg, HttpSession session) {
        BaseResult<User> res;
        session.setAttribute(Constants.USER, null);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        res = new BaseResult(true, "success");
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/nologin", method = {RequestMethod.POST, RequestMethod.GET})
    public BaseResult<String> nologin(@ModelAttribute UserVo user, HttpServletRequest request) {

        return new BaseResult<String>(false, "未登录!", 401);
    }

    @ResponseBody
    @RequestMapping(value = "/failure", method = {RequestMethod.POST, RequestMethod.GET})
    public BaseResult<String> failure(@ModelAttribute UserVo user, HttpServletRequest request) {
        return new BaseResult<String>(false, "无此项操作权限,请向超级管理员申请此项操作权限!", 403);
    }

    /**
     *
     */
    @SameUrlData
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public BaseResult<User> login(@ModelAttribute UserVo user, HttpServletRequest request) {
        if (user.getImgCode() != null && "211064".equals(user.getImgCode())) {
            // 测试数据，直接放行
        } else {
            if (!user.getImgCode().toLowerCase().equals(request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY).toString().toLowerCase())) {
                return new BaseResult<>(false, "图片验证码错误", 403);
            }
            if (user.getUserName() == null || user.getPassword() == null) {
                return new BaseResult<>(false, "参数非法!", 403);
            }
        }
        if (StringUtils.isNoneBlank(user.getUserName())) {
            user.setPhone(null);
        } else {
            user.setUserName(null);
        }
        UserVo loginUser = userService.queryUserByPhoneOrUserName(user);

        if (loginUser == null) {
            return new BaseResult<>(false, "用户不存在", 403);
        }
        if (!loginUser.getPassword().equalsIgnoreCase(user.getPassword())) {
            return new BaseResult<>(false, "密码错误", 403);
        }
        if (!"1".equals(loginUser.getStatus())) {
            return new BaseResult<>(false, "账户状态异常!", 403);
        }
        try {
            loginUser.setRoles(roleService.getRolesByUserID(loginUser.getId()));
            loginUser.setPermissions(permissionService.getPermissionByUserID(loginUser.getId()));
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(StringUtils.isNoneBlank(loginUser.getUserName()) ? loginUser.getUserName() : loginUser.getPhone(), loginUser.getPassword());
            subject.login(token);
            loginUser.setDomain(Constants.domain);
            loginUser.setPassword(token.getCredentials().toString()); // clear password
            request.getSession().setMaxInactiveInterval(12 * 60 * 60); // 设置session 12*60 分钟过期
            request.getSession().setAttribute(Constants.USER, loginUser);
            sysLogService.log("登录", request, Integer.valueOf(loginUser.getId()), Action.loginType);
        } catch (Exception ex) {
            logger.error(ex.getMessage());
        }
        Setting setting = settingService.findById(1);
        if (setting != null) {
            loginUser.setSetting(settingService.findById(1));
        }
        return new BaseResult<>(true, loginUser);
    }

    /***
     * 获取登录用户信息
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get_current", method = RequestMethod.GET)
    public BaseResult getCurrent(@ModelAttribute User user, HttpSession session) {
        if (user.getComName() != null) { // 此时comName 存储登录token

        }
        UserVo user_ = (UserVo) session.getAttribute(Constants.USER);
        if (user_ != null && user_.getId() != 0) {
            return new BaseResult(true, user_);
        } else {
            return new BaseResult<UserVo>(false, "未登录", 401);
        }
    }

    /**
     * 获取会员等级
     *
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getSaleLevel", method = RequestMethod.GET)
    public ListResult<SaleLevel> getSaleLevel(HttpSession session) {
        List list = slService.selectAll();
        return new ListResult(true, list);
    }

    @ResponseBody
    @RequestMapping(value = "/saveSaleLevel", method = RequestMethod.POST)
    public BaseResult<Object> saveSaleLevel(String ids, String percents, HttpSession session) {
        UserVo user_ = (UserVo) session.getAttribute(Constants.USER);

        String[] id = ids.split(",");
        String[] percent = percents.split(",");
        for (int i = 0; i < id.length; i++) {
            SaleLevel sl = new SaleLevel();
            sl.setId(Integer.valueOf(id[i]));
            sl.setPercent(Double.valueOf(percent[i]));
            slService.updateByPrimaryKeySelective(sl);
        }
        return new BaseResult(true, "");
    }

}
